"""
1.提取到主页面中每个电影背后的那个url
    1.拿到 “2025新片精品” 那一块内容
    2.从刚才拿到的代码中提取到href的值

2.访问子页面，提取到电影名称以及下载地址
    1.拿到子页面源代码
    2.数据提取

"""

import requests
import re

url = "https://dy2018.com/"
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
}

resp = requests.get(url,headers=headers)
resp.encoding = 'gbk'
# print(resp.text)


#1. 提取 2025新片精品 部分html代码
obj1 = re.compile(r'2025新片精品.*?<ul>(?P<html>.*?)</ul>',re.S)
result1 = obj1.search(resp.text)
html = result1.group("html")
# print(html)

#2. 提取a标签中的href的值
obj2 = re.compile(r"<li><a href='(?P<href>.*?)' title=(?P<title>.*?)>.*?</a><span><font color=.*?>.*?</font></span></li>")
result2 = obj2.finditer(html)

# 3. 提取片名与下载地址
obj3 = re.compile(r'<div id="Zoom">.*?◎片　　名　(?P<movie>.*?)<br />.*?<div id="downlist"  style="display:none">.*?<a href="(?P<address>.*?)">.*?</a>',re.S)
# 下标索引值
index = 1

# 将爬取到的值写入文件(只打开一次，否则内容会被覆盖掉)
with open("2025新片精品.txt", encoding='utf-8', mode="w") as f:
    for item in result2:
        href = item.group("href")
        title = item.group("title")
        # print(href,title)
        # 拼接子页面的url
        child_url = url.strip('/')+ href
        child_resp = requests.get(child_url,headers=headers)
        child_resp.encoding = "gbk"
        result = obj3.search(child_resp.text)
        movie = result.group("movie")
        address = result.group("address")
        # print(child_resp.text)
        # print(movie)
        # print(address)
        # break
        f.write(f"电影名{index}：{movie}")
        f.write("\n")
        f.write(f"下载地址{index}：{address}")
        f.write("\n")
        index+=1




